package com.wang.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.wang.conf.AppConf;
import com.wang.packpojo.ShortMsg;
import com.wang.pojo.Device;

import com.wang.pojo.User;
import com.wang.service.UserService;
import com.wang.service.UserServiceImpl;

public class ShortMsgUtil {



    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAI4G6j3BPZm4AyL2GKLFhi";
    static final String accessKeySecret = "SzgxiRykbBEAxBsF5wMnihnPP6eDu2";

    //水质在线异常通知
    static final String DevAbnormal = AppConf.DevAbnormal;

    static final String signName = AppConf.signName;


/*    //发送离线通知
    public static String sendOfflineMsg(Devicecontrollerlist dev,Integer noticeId){




        //获取手机号
        UserService userService = SpringUtil.getBean("userServiceImpl", UserServiceImpl.class);
        User user = userService.selectUserByUserId(dev.getUserId());
        String phoneNum = user.getUserPhone();
        if(EmptyUtil.isNotNull(phoneNum)) {

            ShortMsg shortMsg = new ShortMsg();

            shortMsg.setName(dev.getControllerDesc());
            shortMsg.setTime(DateUtil.getStrDate());
            shortMsg.setContent("设备已经离线");

            String result = sendMsg(phoneNum, DevAbnormal, shortMsg).toLowerCase();
            if (result.equals("ok")) {
                PrintUtil.print("发送离线通知短信成功 : " + dev.getDclId()+":"+phoneNum);

                //存储日志
                NoticeLog noticeLog = new NoticeLog();
                noticeLog.setNoticeId(noticeId);
                noticeLog.setDclId(dev.getDclId());
                noticeLog.setNoticeLogContent("离线通知：设备已经离线");
                noticeLog.setNoticeLogTime(DateUtil.getStrDate());
                noticeLog.setNoticeLogResult("success");

                NoticeLogService noticeLogService = SpringUtil.getBean("noticeLogServiceImpl", NoticeLogServiceImpl.class);
                noticeLogService.addNoticeLog(noticeLog);

                return "success";
            } else {

                //存储日志
                NoticeLog noticeLog = new NoticeLog();
                noticeLog.setNoticeId(noticeId);
                noticeLog.setDclId(dev.getDclId());
                noticeLog.setNoticeLogContent("离线通知：设备已经离线");
                noticeLog.setNoticeLogTime(DateUtil.getStrDate());
                noticeLog.setNoticeLogResult("error");

                NoticeLogService noticeLogService = SpringUtil.getBean("noticeLogServiceImpl", NoticeLogServiceImpl.class);
                noticeLogService.addNoticeLog(noticeLog);

                PrintUtil.print("发送离线通知短信失败 : " + dev.getDclId());
                return "error";
            }
        }else {
            //存储日志
            NoticeLog noticeLog = new NoticeLog();
            noticeLog.setDclId(dev.getDclId());
            noticeLog.setNoticeLogContent("离线通知：设备已经离线");
            noticeLog.setNoticeLogTime(DateUtil.getStrDate());
            noticeLog.setNoticeLogResult("error");

            NoticeLogService noticeLogService = SpringUtil.getBean("noticeLogServiceImpl", NoticeLogServiceImpl.class);
            noticeLogService.addNoticeLog(noticeLog);

            PrintUtil.print("发送离线通知短信失败 : " + dev.getDclId());
            return "error";
        }

    }*/


    public static void main(String[] args) {
        ShortMsg shortMsg = new ShortMsg();

        shortMsg.setName("测试设备1");
        shortMsg.setTime("2023-01-02 10:20:23");
        shortMsg.setContent("参数：ph(8.2)状态:偏高");
        System.out.println("参数：ph(8.2)状态:偏高");

        sendMsg("15658018193",DevAbnormal,shortMsg);
    }


    //发送数据异常通知
    public static String sendAbnormalMsg(String msg, Device dev,User user){

        String phoneNum = user.getUserPhone();
        if(EmptyUtil.isNotNull(phoneNum)) {

            ShortMsg shortMsg = new ShortMsg();

            shortMsg.setName(dev.getDevName());
            shortMsg.setTime(DateUtil.getStrDate());
            shortMsg.setContent(msg);

            String result = sendMsg(phoneNum, DevAbnormal, shortMsg).toLowerCase();
            if (result.equals("ok")) {
                PrintUtil.print("发送数据异常短信成功 : " + dev.getDevName()+":"+phoneNum);
                return "success";
            } else {
                PrintUtil.print("发送数据异常短信失败 : " + dev.getDevName()+":"+phoneNum);
                return "error";
            }
        }else {
            return "error";
        }
    }




    //阿里发送验证码功能
    public static String sendMsg(String userPhone,String TemplateCode,ShortMsg shortMsg){

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数

        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);

        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);



        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(userPhone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(TemplateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考：request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")




        //request.setTemplateParam("{\"name\":\""+shortMsg.getName()+"\",\"time\":\""+shortMsg.getTime()+"\",\"content\":\""+shortMsg.getContent()+"\"}");
        request.setTemplateParam(shortMsg.toString());
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        String cod = sendSmsResponse.getCode();


        return cod;


    }
    //发送用户开通短信服务提醒
    public static String sendOpenNoticeMsg(String userPhone,String TemplateCode,String devName){

       //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数

        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);

        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);



        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(userPhone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(TemplateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考：request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")




        //request.setTemplateParam("{\"name\":\""+shortMsg.getName()+"\",\"time\":\""+shortMsg.getTime()+"\",\"content\":\""+shortMsg.getContent()+"\"}");
        request.setTemplateParam("{\"name\":\""+devName+"\"}");
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			//请求成功
				System.out.println("请求短信成功");
			}

        String cod = sendSmsResponse.getCode();


        return cod;


    }

}
